package com.czhouse.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czhouse.mapper.HousesMapper;
import com.czhouse.mapper.VillagesMapper;
import com.czhouse.pojo.Houses;
import com.czhouse.pojo.Villages;
import com.czhouse.vo.PageHouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class HouseServiceImpl implements HouseService {
    @Autowired
    private HousesMapper housesMapper;
    @Autowired
    private VillagesMapper villagesMapper;
    @Transactional
    @Override
    public void addHouseInfo(Houses houses) {
        QueryWrapper<Villages> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("village",houses.getVillage());
        Villages villages = villagesMapper.selectOne(objectQueryWrapper);
        Date date = new Date();
        Villages villages1 = new Villages();
        if (villages==null){

            villages1.setCreated(date).setUpdated(date);
            villagesMapper.insert(villages1.setVillage(houses.getVillage()));
        }
        //MP原则: 入库之后动态回显数据!!
        houses.setVillId(villages1.getViId());
        houses.setCreated(date).setUpdated(date);
        houses.setVillId(villages1.getViId());
        housesMapper.insert(houses);
    }

    @Override
    public PageHouse getAll(Integer userId) {
        QueryWrapper<Houses> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("user_id",userId);
        List<Houses> housesList = housesMapper.selectList(objectQueryWrapper);
        Houses[] houseArr = housesList.toArray(new Houses[]{});
        return new PageHouse(housesList.size(),1,houseArr);
    }

    @Override
    public void update(Houses houses) {
        housesMapper.updateById(houses);
    }
}
